<!--
 * @Descripttion:
 * @version:
 * @Author: sueRimn
 * @Date: 2020-11-06 16:06:21
 * @LastEditors: sueRimn
 * @LastEditTime: 2020-11-18 13:38:33
-->
<template>
  <div class="app-container">
    <div v-pageRoles="['5fab7aa8350e2']">
      <div class="content_box">
        <div class="box_left">
          <el-card class="box-card">
            <p>部门显示</p>
            <TreeList :list="treeList" />
          </el-card>
        </div>
        <div class="box_right">
          <el-card v-if="nowAuth.id" v-pageRoles="['5fab7a9ab776e']" class="box-card">
            <div slot="header" class="card_header">
              <div v-if="quanXianSheZhi == 'teacher'">姓名：{{ nowAuth.nickname }}</div>
              <div v-else>部门名：{{ nowAuth.role_name }}</div>
              <el-button
                v-pageRoles="['5fab7a904b62e']"
                type="primary"
                size="mini"
                @click="dialogFormVisible = true"
              >
                新增部门
              </el-button>
            </div>
            <div>
              <div v-for="(item,index) in moudelName" :key="index">
                <div class="modelName">{{ item.name }}</div>
                <div v-for="(item2,index2) in allAuthList[item.key]" :key="index2">
                  <el-checkbox-group v-model="selectAllAuth">
                    <el-checkbox v-for="(item3,index3) in item2.auth" :key="index3" :label="item3.unid">{{ item3.auth_name }}</el-checkbox>
                  </el-checkbox-group>
                  <!-- <div v-for="(item3,index3) in item2.auth" :key="index3">
                  {{ item3.auth_name }}
                </div> -->
                  <div v-if="item2.auth.length == 0" class="noMore">-- 暂无权限 --</div>

                </div>
              </div>
              <div class="bottomBtn">
                <el-button v-if="nowAuth.id&&quanXianSheZhi == 'role'" v-show="selectAllAuth.length!=0" v-pageRoles="['5fab7a9ab776e']" size="small" type="primary" @click="saveAuth">确认编辑</el-button>
                <el-button v-if="nowAuth.id&&quanXianSheZhi == 'teacher'" v-show="selectAllAuth.length!=0" v-pageRoles="['5fab7a9ab776e']" size="small" type="primary" @click="saveAuthTeacher">确认编辑</el-button>
              </div>
            </div>
            <!-- //新增弹窗 -->
            <el-dialog
              title="新增部门"
              :visible.sync="dialogFormVisible"
              width="500px"
            >
              <el-form>
                <el-form-item
                  label="一级部门"
                  :label-width="formLabelWidth"
                >
                  <el-input
                    v-model="newRoles.one.value"
                    autocomplete="off"
                    placeholder="请输入部门名称"
                  />
                </el-form-item>
                <el-form-item
                  v-if="newRoles.one.value != ''"
                  label="二级部门"
                  :label-width="formLabelWidth"
                >
                  <el-input
                    v-model="newRoles.two.value"
                    autocomplete="off"
                    placeholder="请输入部门名称"
                  />
                </el-form-item>
                <el-form-item
                  v-if="newRoles.one.value != ''&&newRoles.two.value != ''"
                  label="职位"
                  :label-width="formLabelWidth"
                >
                  <el-input
                    v-model="newRoles.three.value"
                    autocomplete="off"
                    placeholder="请输入部门名称"
                  />
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button
                  @click="dialogFormVisible = false"
                >取 消</el-button>
                <el-button
                  type="primary"
                  @click="addRolesArr"
                >确 定</el-button>
              </div>
            </el-dialog>
          </el-card>
        </div>
      </div>
      <!-- //选择老师 -->
      <el-dialog
        title="选择老师"
        :visible.sync="teacherDialogVisible"
        width="80%"
      >
        <div class="search">
          <div class="search_left">
            <el-form :inline="true" :model="searchForm" class="demo-form-inline">
              <el-form-item label="教师姓名">
                <el-input v-model="searchForm.name" placeholder="教师姓名" />
              </el-form-item>
              <el-form-item label="联系方式">
                <el-input v-model="searchForm.telephone" type="tel" placeholder="联系方式" />
              </el-form-item>
            </el-form>
          </div>
          <div class="search_right">
            <el-button type="primary" @click="searchList">查询</el-button>
            <el-button type="info" @click="ResetList">重置</el-button>
          </div>
        </div>
        <div class="staffTable">
          <el-table
            :data="tableData"
            border
            class="table"
          >
            <el-table-column
              width="50"
              label="序号"
              align="center"
            >
              <template slot-scope="scope">
                {{ scope.$index + 1 + pageSize*(currentPage - 1 ) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="nickname"
              label="教师姓名"
            />
            <el-table-column
              prop="user_name"
              label="用户名"
            />
            <el-table-column
              prop="phone"
              label="联系电话"
            />
            <el-table-column
              prop="email"
              label="邮箱"
              width="150"
            />
            <el-table-column
              label="创建时间"
              width="200"
            >
              <template slot-scope="scope">
                {{ scope.row.creat_time*1000 | get_YMDHMS }}
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="100"
              align="center"
            >
              <template slot-scope="scope">
                <el-button v-if="!isSlectTeacher(scope.row.id)" size="small" type="primary" @click="addRoleTeacher(scope.row.id)">添加</el-button>
                <div v-else>已选择</div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="bottomPagination">
          <el-pagination
            :page-sizes="[10,30,50]"
            :page-size="pageSize"
            :current-page="currentPage"
            layout=" sizes, prev, pager, next,total, jumper"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="teacherDialogVisible = false">取 消</el-button>
        </span>
      </el-dialog>
    </div>
    <noRolesTips v-noRolesTips="['5fab7aa8350e2']" />

  </div>
</template>

<script>
import { get_allInstitutionalRole, add_institutionalRole,
    del_institutionalRole, adds_institutionalRoles,
    add_roletoteacher, del_roletoteacher,
    get_allInstitutionalAuth, get_oneInstitutionalAuth,
    seve_InstitutionalAuth, get_teacherInstitutionalAuth,
    save_teacherInstitutionalAuth } from '@/api/institutionalRole'
import { get_PersonnelList } from '@/api/personnelManagement'
import { get_moduleList } from '@/api/module'
import TreeList from './components/index'
import Bus from './bus.js'
import { formatDate } from '@/utils/getTime'
import noRolesTips from '@/components/noRolesTips'
export default {
    name: 'PersonnelStructure',
    components: {
        TreeList,
        noRolesTips
    },
    filters: {
        get_YMDHMS: function(value) {
            if (!value) return ''
            value = formatDate(value)
            return value
        }
    },
    props: {},
    data() {
        return {
            dialogFormVisible: false,
            teacherDialogVisible: false, // 选择老师
            formLabelWidth: '80px',
            treeList: [],
            newRoles: {
                one: {
                    value: '',
                    level: 1
                },
                two: {
                    value: '',
                    level: 2
                },
                three: {
                    value: '',
                    level: 3
                }
            },
            // 选择老师
            total: 0, // 总数
            pageSize: 10, // 每页条数
            currentPage: 1, // 页数
            fireStaffVisible: false,
            searchForm: {
                name: '',
                telephone: ''
            },
            tableData: [],
            addTeacherFrom: {}, // 添加教师的角色信息
            // 模块名
            moudelName: [],
            selectAllAuth: [], // 选择的权限
            // 机构所有权限
            allAuthList: {},
            // 现在编辑的种类
            quanXianSheZhi: 'role', // role 角色 ，teacher 老师
            // 现在正编辑的角色
            nowAuth: {
                role_name: ''
            }
        }
    },
    created() {
        Bus.$on('newAdd', (item, level) => {
            console.log(item, level)
            this.$prompt('请输入部门名称', '新增部门', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputPattern: /\S/,
                inputErrorMessage: '部门名不能为空'
            }).then(({ value }) => {
                this.add_role(item, level, value)
            }).catch(() => {})
        })
        Bus.$on('oldEdit', (item, level) => {
            console.log(item, level)
            this.$prompt('请输入部门名称', '编辑部门', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputPattern: /\S/,
                inputErrorMessage: '部门名不能为空'
            }).then(({ value }) => {
                this.edit_role(item, level, value)
            }).catch(() => {})
        })
        Bus.$on('addTeacher', (item, level) => {
            this.ResetList()
            console.log('新增老师', item, level)
            this.addTeacherFrom = {
                item, level
            }
            this.teacherDialogVisible = true
        })
        Bus.$on('delRoles', (item, level) => {
            console.log('删除角色', item, level)
            if (item.sub.length != 0 || item.teacher.length != 0) {
                return this.$message.error('该角色下拥有下级角色或教师，无法删除')
            }

            this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async() => {
                var queryData = {
                    id: item.id
                }
                var data = await del_institutionalRole(queryData)
                console.log('删除', data)
                if (data.code == 200) {
                    this.get_allRole()
                    this.$message({
                        type: 'success',
                        customClass: 'customClass',
                        message: '删除成功!'
                    })
                }
            }).catch(() => {})
        })
        Bus.$on('deleTeacher', (item, level, teaItem) => {
            console.log('删除教师', item, level, teaItem)

            this.$confirm('此操作将移除该教师权限, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async() => {
                var queryData = {
                    teacher_id: teaItem.id
                }
                if (level == 2) {
                    queryData.role = item.id
                } else {
                    queryData.role = item.id
                    queryData.second = item.pid
                }
                console.log('移除赋权教师参数', queryData)
                var data = await del_roletoteacher(queryData)
                console.log('移除赋权教师参数请求', data)
                if (data.code == 200) {
                    this.get_allRole()
                    this.$message({
                        type: 'success',
                        customClass: 'customClass',
                        message: '移除成功!'
                    })
                }
            }).catch(() => {})
        })
        // 获取当前角色权限
        Bus.$on('roleAuth', async(item) => {
            // for (let index = 0; index < this.moudelName.length; index++) {
            //     let element = this.moudelName[index]
            //     element.checkList = []
            // }
            this.quanXianSheZhi = 'role'
            this.selectAllAuth = []
            this.nowAuth = item
            var queryData = { role_id: item.id }
            var data = await get_oneInstitutionalAuth(queryData)
            console.log('查看角色权限', item, data.data)
            var arr = []
            data.data.forEach(el => {
                arr.push(el.auth_id)
            })
            this.selectAllAuth = arr
        })
        // 获取当前老师权限
        Bus.$on('teacherAuth', async(item) => {
            this.quanXianSheZhi = 'teacher'
            this.selectAllAuth = []
            this.nowAuth = item
            var queryData = { teacher_id: item.id }
            var data = await get_teacherInstitutionalAuth(queryData)
            console.log('查看老师权限', item, data.data)
            var arr = []
            data.data.forEach(el => {
                arr.push(el.auth_id)
            })
            this.selectAllAuth = arr
        })
        this.getModuleList()
        this.getPeopleList()
        this.get_allRole()
    },
    beforeDestroy() {
        Bus.$off('newAdd') // 注意这里off掉了'home-on'的订阅事件
        Bus.$off('oldEdit')
        Bus.$off('addTeacher')
        Bus.$off('delRoles')
        Bus.$off('deleTeacher')
        Bus.$off('roleAuth')
        Bus.$off('teacherAuth')
    },
    methods: {
        // 拿到模块
        async getModuleList() {
            var dataList = await get_moduleList({})
            console.log('模块列表：', dataList)
            if (dataList.code == 200) {
                var roles = this.$store.getters.sideBarRoles
                var list = dataList.data.list
                list.forEach((el, index) => {
                    if (roles.includes(el.unid)) {
                        var obj = {
                            name: el.module_name,
                            key: el.unid
                        }
                        this.moudelName.push(obj)
                    }
                })
                this.get_allAuth()
            }
        },
        // 获取所有角色
        async get_allRole() {
            var queryData = {}
            var data = await get_allInstitutionalRole(queryData)
            this.treeList = data.data
            console.log('获取机构角色：', data.data)
        },
        // 获取机构权限
        async get_allAuth() {
            var queryData = {}
            var data = await get_allInstitutionalAuth(queryData)
            this.allAuthList = data.data
            console.log('获取机构权限', data)
        },
        async saveAuth() {
            var queryData = {
                role_id: this.nowAuth.id,
                auth: this.selectAllAuth,
                update: 1
            }
            var data = await seve_InstitutionalAuth(queryData)
            console.log('保存角色权限', data, queryData)
            if (data.code == 200) {
                this.$message({
                    type: 'success',
                    customClass: 'customClass',
                    message: '保存成功!'
                })
            }
        },
        async saveAuthTeacher() {
            var queryData = {
                teacher_id: this.nowAuth.id,
                auth: this.selectAllAuth
            }
            var data = await save_teacherInstitutionalAuth(queryData)
            console.log('保存角色权限', data, queryData)
            if (data.code == 200) {
                this.$message({
                    type: 'success',
                    customClass: 'customClass',
                    message: '保存成功!'
                })
            }
        },
        async add_role(item, level, value) {
            var queryData = {
                role_name: value,
                institution_id: this.$store.getters.institute_id,
                type: level + 1,
                pid: item.id
            }
            console.log('新增条件', queryData)
            var data = await add_institutionalRole(queryData)
            console.log('新增roles：', data)
            if (data.code == 200) {
                this.$message({
                    type: 'success',
                    customClass: 'customClass',
                    message: '操作成功!'
                })
            }
            this.get_allRole()
        },
        async edit_role(item, level, value) {
            var queryData = {
                id: item.id,
                role_name: value,
                institution_id: this.$store.getters.institute_id,
                type: level + 1
                // pid: item.id
            }
            console.log('编辑条件', queryData)
            var data = await add_institutionalRole(queryData)
            if (data.code == 200) {
                this.$message({
                    type: 'success',
                    customClass: 'customClass',
                    message: '操作成功!'
                })
            }
            console.log('编辑roles：', data)
            this.get_allRole()
        },
        async addRolesArr() {
            if (this.newRoles.one.value == '') {
                return this.$message.error('请完善角色信息')
            }
            var arr = []
            for (var key in this.newRoles) {
                if (this.newRoles[key].value != '') {
                    arr.push({
                        role_name: this.newRoles[key].value,
                        institution_id: this.$store.getters.institute_id,
                        type: this.newRoles[key].level
                    })
                } else {
                    break
                }
            }

            var queryData = {
                role: arr,
                type: 1
            }
            var data = await adds_institutionalRoles(queryData)
            if (data.code == 200) {
                this.dialogFormVisible = false
                this.newRoles = {
                    one: {
                        value: '',
                        level: 1
                    },
                    two: {
                        value: '',
                        level: 2
                    },
                    three: {
                        value: '',
                        level: 3
                    }
                }
                this.get_allRole()
                this.$message({
                    type: 'success',
                    customClass: 'customClass',
                    message: '操作成功!'
                })
            }
            console.log('新增多个角色', data)
        },
        async getPeopleList() {
            var queryData = {
                page: this.currentPage,
                pagesize: this.pageSize,
                type: 3
            }
            if (this.searchForm.name != '') {
                queryData.nickname = this.searchForm.name
                console.log('查询名字')
            }
            if (this.searchForm.telephone != '') {
                queryData.phone = this.searchForm.telephone
                console.log('查询电话')
            }
            console.log('查询条件：', this.searchForm, queryData)
            var resData = await get_PersonnelList(queryData)
            console.log('获取用户列表：', resData)
            if (resData.code == 200) {
                this.total = resData.data.total
                this.tableData = resData.data.list
            }
        },
        searchList() {
            this.currentPage = 1
            this.getPeopleList()
        },
        ResetList() {
            this.searchForm = {
                name: '',
                telephone: ''
            }
            this.currentPage = 1
            this.getPeopleList()
        },
        handleCurrentChange(val) {
            this.currentPage = val
            this.getPeopleList()
        },
        handleSizeChange(val) {
            this.currentPage = 1
            this.pageSize = val
            this.getPeopleList()
        },
        isSlectTeacher(id) {
            var result = this.addTeacherFrom.item.teacher.some((item) => {
                if (item.id == id) {
                    return true
                }
            })

            return result
        },
        async addRoleTeacher(id) {
            var queryData = {
                teacher_id: id
            }
            if (this.addTeacherFrom.level == 2) {
                queryData.role = this.addTeacherFrom.item.id
            } else {
                queryData.role = this.addTeacherFrom.item.id
                queryData.second = this.addTeacherFrom.item.pid
            }
            console.log('赋权教师参数', queryData, id)
            var data = await add_roletoteacher(queryData)
            console.log('赋权教师', data)
            this.teacherDialogVisible = false
            this.get_allRole()
        }
    }
}
</script>

<style lang="scss" scoped>
.content_box {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    // justify-content: space-between;
    .box-card {
        min-height: 700px;

        .card_header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

    }

    .box_left {
        min-width: 550px;
        margin-right: 20px;
        margin-bottom: 20px;
    }

    .box_right {
        // flex-grow: 1;
        width: calc(100% - 600px);
        min-width: 550px;

        .modelName {
            font-size: 15px;
            font-weight: 600;
            margin: 15px 0;
        }

        .noMore {
            width: 100%;
            text-align: center;
        }

        .bottomBtn {
            width: 100%;
            text-align: right;
            margin-top: 20px;
        }
    }
}

.search{
    display: flex;
    justify-content:space-between;
    align-items: center;
    width: 100%;
    .search_left{
         display: flex;
         align-items: center;
          .el-form-item{
           margin-bottom: 0 !important;
      }
    }
     .search_right{
    }
    }
    .staffTable{
        .addStaff{
            margin-top: 20px;
            margin-right: 52px;
        }
      .table{
          width: 100%;
          margin-top:10px
      }
    }
    .bottomPagination {
    padding: 15px 0;
}

//覆盖多选样式
.el-checkbox {
    margin-bottom: 10px;
}
</style>
